﻿using System;
using System.Linq;
using System.Web.Mvc;
using CodeFirstEntityConfiguration.Infrastructure;
using CodeFirstEntityConfiguration.Models;

namespace CodeFirstEntityConfiguration.Controllers
{
    public class PostController : Controller
    {
        private readonly PostDb _postDb = new PostDb();

        public ActionResult Index()
        {
            var posts = from d in _postDb.Posts
                        select d;

            return View(posts);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Post post)
        {
            if(ModelState.IsValid)
            {
                post.CreatedOn = DateTime.Now;
                _postDb.Posts.Add(post);
                _postDb.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(post);  
        }

        public ActionResult Edit(int id)
        {
            var post = _postDb.Posts.Single(pst => pst.Id == id);
            return View(post);
        }

        [HttpPost]
        public ActionResult Edit(Post updatedPost)
        {
            if(ModelState.IsValid)
            {
                var oldPost = _postDb.Posts.Single(post => post.Id == updatedPost.Id);
                oldPost.Title = updatedPost.Title;
                oldPost.Body = updatedPost.Body;
                oldPost.CreatedBy = updatedPost.CreatedBy;
                _postDb.SaveChanges();

                return RedirectToAction("Index");
            }
            return View(updatedPost);
        }

        public ActionResult Details(int id)
        {
            var postDetail = _postDb.Posts.Single(post => post.Id == id);
            return View(postDetail);
        }
    }
}
